<script setup>
import { ref, watch, onUnmounted } from 'vue'
import { User, Camera } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores'
import {
  userDeleteAvatarService,
  userUpdateInfoService,
  userUploadAvatarService,
  userGetMdStrService
} from '@/api/user'
import { aiUpdateExpertService } from '@/api/ai'
import { baseURL } from '@/utils/request'
import MdEditor from '@/components/MdEditor.vue'
const userStore = useUserStore()

//标准数据
const standardData = ref('')

// 表单数据
const form = ref('')
// 头像相关
const avatarPreview = ref('')
const avatarDefault = ref('')

//渲染数据
const getUserInfo = async () => {
  await userStore.getUserInfoService()
  form.value = { ...userStore.userInfo }
  standardData.value = { ...userStore.userInfo }
  avatarPreview.value = baseURL + '/' + userStore.userInfo.picUrl
  avatarDefault.value = baseURL + '/' + userStore.userInfo.picUrl
}
getUserInfo()

// 表单验证规则
const formRules = {
  username: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在2-20个字符', trigger: 'blur' }
  ],
  age: [
    { required: true, message: '请输入年龄', trigger: 'blur' },
    {
      type: 'number',
      min: 18,
      max: 100,
      message: '年龄需在18-100之间',
      trigger: 'blur'
    }
  ],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
  nationality: [{ required: true, message: '请输入民族', trigger: 'blur' }],
  professional: [{ required: true, message: '请选择职称', trigger: 'change' }],
  organization: [
    { required: true, message: '请输入学院名称', trigger: 'blur' }
  ],
  academic: [{ required: true, message: '请选择最高学历', trigger: 'change' }],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    {
      type: 'email',
      message: '请输入正确的邮箱地址',
      trigger: ['blur', 'change']
    }
  ],
  research: [{ required: true, message: '请输入研究方向', trigger: 'blur' }]
}

// 表单引用
const formRef = ref()

// 保存编辑
const saveEdit = async () => {
  await formRef.value.validate()

  // 检查MD编辑器是否有未保存的改动
  if (
    form.value.markdownContent !== 'unselected' &&
    !mdEditorRef.value.hasUnsavedChanges()
  ) {
    ElMessage.warning('研究领域有未保存的改动，请先保存研究领域内容')
    return
  }

  // 判断基本信息、头像是否有变化
  const baseInfoChanged =
    JSON.stringify({ ...form.value, picUrl: undefined }) !==
    JSON.stringify({ ...standardData.value, picUrl: undefined })
  // 头像：只要点击上传就上传
  let avatarChanged = false
  if (avatarPreview.value !== avatarDefault.value) {
    avatarChanged = true
  }
  // MD内容变化判断
  const mdContentChanged =
    form.value.markdownContent !== standardData.value.markdownContent

  if (!baseInfoChanged && !avatarChanged && !mdContentChanged) {
    ElMessage.info('没有任何更改，无需保存')
    return
  }
  // 头像上传
  if (avatarChanged) {
    await userDeleteAvatarService(form.value.userId)
    const FD = new FormData()
    FD.append('file', form.value.picUrl)
    const {
      data: { data }
    } = await userUploadAvatarService(FD, 0)
    form.value.picUrl = data
  }
  // 基本信息有变化
  if (baseInfoChanged || avatarChanged || mdContentChanged) {
    await userUpdateInfoService(form.value)
    ElMessage.success('保存成功')
    getUserInfo()
  }
}

// 头像上传前验证
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isJPG) {
    ElMessage.error('上传头像只能是 JPG/PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('上传头像大小不能超过 2MB!')
  }
  return isJPG && isLt2M
}

// 头像上传改变
const handleAvatarChange = (file) => {
  avatarPreview.value = URL.createObjectURL(file.raw)
  form.value.picUrl = file.raw
}

//共用定时器（查看是否更新md文档）
const timer = setInterval(() => {
  userStore.getUserInfoService()
  form.value.markdownContent = userStore.userInfo.markdownContent
}, 5000)

// MD编辑器引用
const mdEditorRef = ref()
const isMdLoading = ref(true)
//渲染数据（MD文档）
// 定义isUpload变量
const isUpload = ref(true)

watch(
  () => form.value.markdownContent,
  (newVal) => {
    if (newVal === 'unselected') {
      isUpload.value = false
      isMdLoading.value = false
      clearTimeout(timer)
    } else if (newVal) {
      isMdLoading.value = false
      if (timer) {
        clearInterval(timer) // 清除setInterval
      }
    } else {
      isMdLoading.value = true
    }
  },
  { immediate: true }
)
//组件销毁时清除定时器
onUnmounted(() => {
  if (timer) {
    clearInterval(timer) // 清除setInterval
  }
})

//个人信息页面上传文件
const mdFile = ref(null)
function beforeMdFileUpload(file) {
  // 常见文本文件扩展名
  const textExts = [
    '.txt',
    '.md',
    '.json',
    '.csv',
    '.log',
    '.xml',
    '.yaml',
    '.yml',
    '.ini',
    '.conf',
    '.py',
    '.js',
    '.ts',
    '.java',
    '.c',
    '.cpp',
    '.h',
    '.css',
    '.scss',
    '.less',
    '.html',
    '.vue'
  ]
  const lowerName = file.name.toLowerCase()
  const isText = textExts.some((ext) => lowerName.endsWith(ext))
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isText) {
    ElMessage.error('只能上传常见文本文件!')
  }
  if (!isLt2M) {
    ElMessage.error('上传文件大小不能超过 2MB!')
  }
  return isText && isLt2M
}

const handleMdFileChange = async (file) => {
  isUpload.value = true
  form.value.markdownContent = ''

  //用户加载时切屏继续正常显示
  await userUpdateInfoService(form.value)

  mdFile.value = file.raw
  const FD = new FormData()
  FD.append('file', file.raw)
  await userGetMdStrService(FD, form.value.userId, 'EXPERT')
  await userStore.getUserInfoService()
  form.value.markdownContent = userStore.userInfo.markdownContent
}

// 自动更新loading状态
const isAutoUpdating = ref(false)
//自动更新
const aiUpdateExpert = async () => {
  try {
    isAutoUpdating.value = true
    await aiUpdateExpertService(form.value.userId)
    ElMessage.success('自动更新成功')
    // 重新获取用户信息
    await userStore.getUserInfoService()
    form.value = { ...userStore.userInfo }
  } catch (error) {
    ElMessage.error('自动更新失败')
    console.error('自动更新失败:', error)
  } finally {
    isAutoUpdating.value = false
  }
}
</script>

<template>
  <div
    class="main1"
    v-loading="isAutoUpdating"
    element-loading-text="AI正在自动更新个人信息，请稍等..."
  >
    <div class="user-info-page-header">
      <span class="user-info-title">个人信息</span>
      <div>
        <el-button type="primary" @click="aiUpdateExpert">自动更新</el-button>
        <el-button type="primary" @click="saveEdit">保存</el-button>
      </div>
    </div>
    <!-- 头像卡片 -->
    <el-card class="avatar-card" shadow="hover">
      <div class="avatar-flex">
        <div class="avatar-container">
          <div class="avatar-wrapper">
            <img v-if="avatarPreview" :src="avatarPreview" class="avatar-img" />
            <div v-else class="avatar-placeholder">
              <el-icon><User /></el-icon>
            </div>
          </div>
        </div>
        <div class="upload-section">
          <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            :auto-upload="false"
            :before-upload="beforeAvatarUpload"
            :on-change="handleAvatarChange"
          >
            <el-button type="primary" class="upload-btn">
              <el-icon><Camera /></el-icon>
              上传头像
            </el-button>
          </el-upload>
        </div>
      </div>
    </el-card>
    <!-- 基本信息卡片 -->
    <el-card class="info-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <el-icon><User /></el-icon>
          <span class="skyColor">基本信息</span>
        </div>
      </template>
      <el-form
        ref="formRef"
        :model="form"
        :rules="formRules"
        label-width="0px"
        class="info-form"
      >
        <div class="form-row">
          <el-form-item label="ID" prop="userId" label-position="top">
            <el-input v-model="form.userId" disabled class="input-style" />
          </el-form-item>
          <el-form-item label="姓名" prop="username" label-position="top">
            <el-input v-model="form.username" class="input-style" />
          </el-form-item>
          <el-form-item label="年龄" prop="age" label-position="top">
            <el-input-number
              v-model="form.age"
              :min="18"
              :max="100"
              class="input-style"
            />
          </el-form-item>
          <el-form-item label="性别" prop="gender" label-position="top">
            <el-select
              v-model="form.gender"
              placeholder="请选择性别"
              class="input-style"
            >
              <el-option label="男" value="男" />
              <el-option label="女" value="女" />
            </el-select>
          </el-form-item>
        </div>
        <div class="form-row">
          <el-form-item label="民族" prop="nationality" label-position="top">
            <el-input v-model="form.nationality" class="input-style" />
          </el-form-item>
          <el-form-item label="职称" prop="professional" label-position="top">
            <el-select
              v-model="form.professional"
              placeholder="请选择职称"
              class="input-style"
            >
              <el-option label="教授" value="教授" />
              <el-option label="副教授" value="副教授" />
              <el-option label="讲师" value="讲师" />
              <el-option label="助教" value="助教" />
              <el-option label="研究生导师" value="研究生导师" />
              <el-option label="其他" value="其他" />
            </el-select>
          </el-form-item>
          <el-form-item label="学院" prop="organization" label-position="top">
            <el-input v-model="form.organization" class="input-style" />
          </el-form-item>
          <el-form-item label="最高学历" prop="academic" label-position="top">
            <el-select
              v-model="form.academic"
              placeholder="请选择最高学历"
              class="input-style"
            >
              <el-option label="博士" value="博士" />
              <el-option label="硕士" value="硕士" />
              <el-option label="学士" value="学士" />
              <el-option label="其他" value="其他" />
            </el-select>
          </el-form-item>
        </div>
        <div class="form-row">
          <el-form-item label="研究领域" prop="research" label-position="top">
            <el-input v-model="form.research" class="input-style" />
          </el-form-item>
          <el-form-item label="邮箱" prop="email" label-position="top">
            <el-input v-model="form.email" class="input-style" />
          </el-form-item>
        </div>
      </el-form>
    </el-card>
    <!-- 研究领域卡片/遮罩层 -->
    <el-card
      v-if="isUpload"
      class="info-card"
      shadow="hover"
      v-loading="isMdLoading"
      element-loading-text="AI正在处理您的研究领域,请稍等..."
    >
      <template #header>
        <div class="card-header">
          <el-icon><User /></el-icon>
          <span class="skyColor">研究领域</span>
        </div>
      </template>
      <MdEditor ref="mdEditorRef" v-model:MdContent="form.markdownContent" />
    </el-card>
    <el-card
      v-else
      class="info-card"
      shadow="hover"
      v-loading="isMdLoading"
      element-loading-text="AI正在处理您的研究领域,请稍等..."
    >
      <template #header>
        <div class="card-header">
          <el-icon><User /></el-icon>
          <span class="skyColor">研究领域</span>
        </div>
      </template>
      <el-empty>
        <el-upload
          class="md-uploader"
          :show-file-list="false"
          :before-upload="beforeMdFileUpload"
          :on-change="handleMdFileChange"
          :auto-upload="false"
        >
          <el-button type="primary" class="md-upload-btn">
            上传MD文件
          </el-button>
        </el-upload>
        <div v-if="mdFile" class="file-selected-tip">
          已选择文件：{{ mdFile.name }}
        </div>
      </el-empty>
    </el-card>
  </div>
</template>

<style scoped lang="less">
.main1 {
  padding: 20px;
}
.user-info-page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
}
.user-info-title {
  font-size: 22px;
  font-weight: bold;
  color: #2176d2;
}

.avatar-card {
  margin-bottom: 20px;
}

.avatar-flex {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 50px;
  gap: 60px;
}

.avatar-container {
  display: flex;
  align-items: center;
}

.avatar-wrapper {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  overflow: hidden;
  border: 3px solid #e4e7ed;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
}

.avatar-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
  color: #909399;
  font-size: 48px;
}

.upload-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
}

.upload-btn {
  display: flex;
  align-items: center;
  gap: 5px;
}

.info-card {
  margin-bottom: 20px;
  overflow-x: auto;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}

.info-form {
  padding: 20px 0;
}

.form-row {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  margin-bottom: 20px;
}

.form-row:last-child {
  margin-bottom: 0;
}

.input-style {
  width: 100%;
  min-width: 0;
}

/deep/ .el-form-item__label {
  color: #999;
  font-size: 14px;
  font-weight: 400;
  margin-bottom: 4px;
  line-height: 1.2;
}

// 响应式设计
@media (max-width: 1200px) {
  .form-row {
    grid-template-columns: repeat(3, 1fr);
  }
}

@media (max-width: 900px) {
  .form-row {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 600px) {
  .form-row {
    grid-template-columns: 1fr;
  }
  .avatar-flex {
    flex-direction: column;
    gap: 20px;
  }
}

.edit-btn-group {
  display: flex;
  gap: 10px;
}
.skyColor {
  color: #2176d2;
}
.readonly-notice {
  margin-bottom: 16px;
}
</style>
